<?php


namespace App\Http\Controllers\Api\Pdf;

use App\Enums\Api\Response;
use App\Http\Controllers\Controller;
use App\Models\Category\Category;
use App\Models\Category\CategoryModule;
use App\Models\Pdf\PdfImage;
use App\Models\Pdf\TextbookRead;
use App\Models\Tool\FileUrl;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PdfController extends Controller
{
    /**
     * 教材点读-目录
     */
    public function catalog(Request $request): JsonResponse
    {
        $gradeId = $request->input('gradeId');
        $title = Category::query()->where('id', $gradeId)->value('name');
        $unitListQuery = Category::query()
            ->select('id', 'name', 'page', 'parent_id')
            ->where('parent_id', $gradeId);
        $unitList = $unitListQuery->get();

        return apiResponse(
            code: Response::SERVICE_SUCCESS->value,
            data: [
                'title' => $this->return_book_name($gradeId) . ' ' . $title,
                'data' => $unitList->toArray()
            ],
            msg: Response::SERVICE_SUCCESS->response(),
            type: 'pdf_catalog'
        );
    }

    /**
     * 教材点读-书页
     */
    public function pdf(Request $request): JsonResponse
    {
        $gradeId = $request->input('gradeId');
        $page = $request->input('page');

        $imageQuery = PdfImage::query()
            ->select('id', 'page', 'url', 'width', 'height')
            ->with('coordinate.click_learn')
            ->where('category_id', $gradeId)
            ->orderBy('real_page');

        if ($gradeId < 70) {
            $imageQuery = $imageQuery->where('page', '>', 1);
        }

        $imageList = $imageQuery->offset($page - 1)->first()->toArray();
        $imageList['next_page'] = TextbookRead::query()
            ->whereHas('category.parent', function (Builder $builder) use ($gradeId) {
                $builder->where('id', $gradeId);
            })
            ->where('page', '>', $page)
            ->orderBy('page')
            ->value('page') ?? 0;

        $file_url = FileUrl::query()->where('module', CategoryModule::ModuleTypeELEVEN)->first();

        $imageList['coordinate'] = array_map(function ($value) use ($gradeId, $file_url) {
            $audio_url = '';
            $translation = '';
            $content = '';

            if ($value['click_learn']) {
                $audio_url = $value['click_learn']['audio_url'];
                $translation = $value['click_learn']['translation'];
                $content = $value['click_learn']['content'];
            }

            return [
                'shapeIndex' => $value['id'],
                'pdf_image_id' => $value['pdf_image_id'],
                'translation' => $translation,
                'content' => $content,
                'text' => $value['text'],
                'type' => 'rectangle',
                'audio_url' => convert_file_address_exist(
                    module: CategoryModule::ModuleTypeELEVEN,
                    file_address: $audio_url,
                    grade: $gradeId,
                    category: '',
                    type: '.mp3',
                    file_url: $file_url
                ),
                'audio' => $value['click_learn_id'] ?? '',
                'points' => json_decode($value['coordinate'], true)
            ];
        }, $imageList['coordinate']);

        $data['data'] = [$imageList];

        if ($gradeId < 70) {
            $data['page']['total_page'] = PdfImage::query()
                    ->select('id', 'page', 'url', 'width', 'height')
                    ->with('coordinate.click_learn')
                    ->where('category_id', $gradeId)->max('page') - 1;
        } else {
            $data['page']['total_page'] = PdfImage::query()
                    ->select('id', 'page', 'url', 'width', 'height')
                    ->with('coordinate.click_learn')
                    ->where('category_id', $gradeId)->max('page') + 1;
        }

        $data['page']['current_page'] = $page;

        return apiResponse(
            code: Response::SERVICE_SUCCESS->value,
            data: $data,
            msg: Response::SERVICE_SUCCESS->response(),
            type: 'pdf'
        );
    }

    /**
     * 教材点读-朗读
     */
    public function read(Request $request): JsonResponse
    {
        $gradeId = $request->input('gradeId');
        $page = $request->input('page');

        $imageQuery = PdfImage::query()
            ->select('real_page')
            ->where('category_id', $gradeId)
            ->limit(2)
            ->orderBy('real_page');

        if ($gradeId < 70) {
            $imageQuery = $imageQuery->where('real_page', '>', 1);
        }

        $real_pages = $imageQuery->offset($page - 1)->pluck('real_page')->toArray();

        $pages = TextbookRead::query()
            ->whereHas('category.parent', function (Builder $builder) use ($gradeId) {
                $builder->where('id', $gradeId);
            })
            ->pluck('click_learn_id')
            ->toArray();

        $click_learn_ids = array_flip($pages);

        $readList = TextbookRead::query()
            ->whereHas('category.parent', function (Builder $builder) use ($gradeId) {
                $builder->where('id', $gradeId);
            })
            ->whereIn('page', $real_pages)
            ->with('click_learn')
            ->get()
            ->toArray();

        $jsonData = [];
        $file_url = FileUrl::query()->where('module', CategoryModule::ModuleTypeELEVEN)->first();

        foreach ($readList as &$read) {
            $data['page'] = $read['page'];
            $data['content'] = $read['click_learn']['content'] ?? '';
            $data['content_id'] = $read['click_learn']['id'] ?? '';
            $data['translation'] = $read['click_learn']['translation'] ?? '';
            $data['audio_url'] = convert_file_address_exist(
                module: CategoryModule::ModuleTypeELEVEN,
                file_address: $read['click_learn']['audio_url'],
                grade: $gradeId,
                category: '',
                type: '.mp3',
                file_url: $file_url
            ) ?? '';
            $data['id'] = $click_learn_ids[$read['click_learn_id']] + 1 ?? '';
            $jsonData[] = $data;
        }

        return apiResponse(
            code: Response::SERVICE_SUCCESS->value,
            data: $jsonData,
            msg: Response::SERVICE_SUCCESS->response(),
            type: 'pdf_read'
        );
    }

    /**
     * 返回书名
     */
    protected function return_book_name(int $gradeId): string
    {
        if ($gradeId <= 40) {
            return '英语（PEP）';
        }
        if ($gradeId < 70) {
            return '英语（PEP）（三年级起点）';
        }
        return '英语';
    }
}
